Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
Functional component not rerendering, even passing [sum] in useEffect dependency as it changes

Even on click of button, the sum variable changes to 29.98, but though I am using useEffect hook, and I've added dependency as [sum], so that if value of num changes let sum = 0, as I click button, and sum now becomes as 29.98, so re-render should happen and I should now see updated value on UI, but it still shows 0, I think component does not Rerender. Why?

import React, { useEffect } from 'react'; 
import './SelectEx1.css'

const SelectEx1 = (props) => {

let data = [
    {
        id: 1,
        title: "Milk",
        price: 15.99,
    },
    {
        id: 2,
        title: "Bread",
        price: 13.99,
    },
];
let sum = 0; 

useEffect(()=>{}, [sum]);

const handleClick = () => {
  console.log(data);
  data.map((item) => {
    sum = (sum + item.price)
  });
}

  return (
    <div>
      <p>hello, {sum}</p>
      <button onClick={handleClick}>click-me</button>
    </div>
  )
}
export default SelectEx1; 
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

I think what you want is

const [sum, setSum] = useState(0); 
...
const handleClick = () => {
  console.log(data);
  const total = data.reduce((a, b) => a + b, 0);
  setSum(total);
}

So that handleClick will trigger a change in state, which triggers rerender. Putting sum into the dependency list of useEffect merely triggers the function(first parameter) in useEffect when sum is changed. Since the first paramter is an empty function, it does nothing when sum is changed.

about 4 years ago · Santiago Trujillo Relatório

0

Instead of defining sum as variable make it state. Because state updates trigger re-renders. And call setSum inside handleClick function to change the state sum's value which will cause re-render and you'll get to see the updated value on the UI:

import React, { useEffect } from 'react'; 
import './SelectEx1.css'

const data = [
    {
        id: 1,
        title: "Milk",
        price: 15.99,
    },
    {
        id: 2,
        title: "Bread",
        price: 13.99,
    },
];
 
const SelectEx1 = (props) => {

const [sum, setSum] = React.useState(0)

const handleClick = () => {
  const total = data?.reduce(function (previousValue, currentValue) {
    return previousValue + currentValue.price
  }, 0)
  setSum(total)
}

  return (
    <div>
      <p>hello, {sum}</p>
      <button onClick={handleClick}>click-me</button>
    </div>
  )
}

export default SelectEx1; 

about 4 years ago · Santiago Trujillo Relatório

0

You don't need useEffect, put sum in useState and change onClick like below:

const [sum,setSum] = useState(0);
const handleClick = () => {
  const reducer = (previousValue, currentValue) => previousValue +
  currentValue.price;
  setSum(data.reduce(reducer,0))
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda